<!DOCTYPE html>
<html>
<head>
  <title>佑玛道订单信息</title>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="chrome=1">
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
</head>
<body>
<script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script>
<script src="http://webapi.amap.com/maps?v=1.3&key=785d1552890d3ce79bfcd57475ae271a"></script>
<script src="http://webapi.amap.com/ui/1.0/main.js"></script>
<script src="./shim.js"></script>
<script src="./xlsx.full.min.js"></script>

<style type="text/css">
  body,html,#container{
    height: 100%;
    margin: 0px
  }
  #container{
    height:100%;
    width:100%;
  }
  #panel{
    position:absolute;
    top:10px;
    right:10px;
    width:260px;
    z-index:999;
  }
  #my-list{
    margin:0;
    padding:0;
  }
  #my-list li{
    background:#eee;
    margin:10px 0;
    list-style:none;
    padding:0;
    padding:10px;
    cursor:pointer;
  }
  #my-list li p{
    margin:5px;
  }
  #my-list li.selected{
    background:green;
    color:#fff;
  }
  .selected .amap-marker-label{
    background:green;
    color:#fff;
    border-color:#ccc;
  }
  #panel h3{
    margin:10px 0;
  }
  #panel dd{
    margin:5px 5px;
  }
  #panel dl{
    margin:7px 0;
  }
  .panel {
    background-color: #ddf;
    color: #333;
    border: 1px solid silver;
    box-shadow: 3px 4px 3px 0px silver;
    position: absolute;
    top: 10px;
    right: 10px;
    border-radius: 5px;
    overflow: hidden;
    line-height: 20px;
  }
  #input{
    width: 250px;
    height: 25px;
    border: 0;
  }

  .button-group {
    position: absolute;
    bottom: 20px;
    right: 20px;
    font-size: 12px;
    padding: 10px;
  }

  .button-group .button {
    height: 28px;
    line-height: 28px;
    background-color: #0D9BF2;
    color: #FFF;
    border: 0;
    outline: none;
    padding-left: 5px;
    padding-right: 5px;
    border-radius: 3px;
    margin-bottom: 4px;
    cursor: pointer;
  }
  .button-group .inputtext {
    height: 26px;
    line-height: 26px;
    border: 1px;
    outline: none;
    padding-left: 5px;
    padding-right: 5px;
    border-radius: 3px;
    margin-bottom: 4px;
    cursor: pointer;
  }
  #panel {
    z-index: 999;
    position: absolute;
    background-color: white;
    max-height: 100%;
    overflow-y: auto;
    right: 0;
    width: 280px;
  }
  #my-list li {
    cursor: default;
  }
  .wx_loading{position:fixed;top:0;left:0;bottom:0;right:0;z-index:10000;background-color:rgba(0, 0, 0, 0)}.wx_loading_inner{text-align:center;background-color:rgba(0, 0, 0, 0.5);color:#fff;position:fixed;top:50%;left:50%;margin-left:-70px;margin-top:-48px;width:140px;border-radius:6px;font-size:14px;padding:58px 0 10px 0}.wx_loading_icon{position:absolute;top:15px;left:50%;margin-left:-16px;width:24px;height:24px;border:2px solid #fff;border-radius:24px;-webkit-animation:gif 1s infinite linear;animation:gif 1s infinite linear;clip:rect(0 auto 12px 0)}@keyframes gif{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg);}100%{-webkit-transform:rotate(360deg);transform:rotate(360deg);}}@-webkit-keyframes gif{0%{-webkit-transform:rotate(0deg);}100%{-webkit-transform:rotate(360deg);}}

  .amap-simple-marker.my-marker .amap-simple-marker-label{
    font-size:12px;
    color:#eee;
    font-family:sans-serif;
  }
  .selected .amap-simple-marker.my-marker .amap-simple-marker-label{
    font-size:14px;
    color:orange;
    font-weight:700;
  }

</style>
<div class="wx_loading" id="wxloading" style="display: none;">
  <div class="wx_loading_inner">
    <i class="wx_loading_icon"></i>
    请求加载中...
  </div>
</div>
<input type="file" id="xlf" name="xlf" />
<div style="height: 95%;width: 100%;">
  <div id="container" tabindex="0"></div>
  <div class ='panel'>
    <div id = 'message'></div>
  </div>
  <div id="panel">
    <ul id="my-list"></ul>
  </div>
  <div class="button-group">
    <input type="button" class="button" value="清空所有坐标" id="clearMarker"/>
  </div>
</div>
<div style="display: none;">
  <b>Advanced Demo Options:</b>
  Use Web Workers: (when available) <input type="checkbox" name="useworker" checked>
  Use Transferrables: (when available) <input type="checkbox" name="xferable" checked>
  Use readAsBinaryString: (when available) <input type="checkbox" name="userabs" checked>
</div>
<script type="text/javascript">
  var X = XLSX;
  var XW = {
    msg: 'xlsx',
    rABS: 'xlsxworker2.js',
    norABS: 'xlsxworker1.js',
    noxfer: 'xlsxworker.js'
  };

  var rABS = typeof FileReader !== "undefined" && typeof FileReader.prototype !== "undefined" && typeof FileReader.prototype.readAsBinaryString !== "undefined";

  if(!rABS) {
    document.getElementsByName("userabs")[0].disabled = true;
    document.getElementsByName("userabs")[0].checked = false;
  }

  var use_worker = typeof Worker !== 'undefined';
  if(!use_worker) {
    document.getElementsByName("useworker")[0].disabled = true;
    document.getElementsByName("useworker")[0].checked = false;
  }

  var transferable = use_worker;
  if(!transferable) {
    document.getElementsByName("xferable")[0].disabled = true;
    document.getElementsByName("xferable")[0].checked = false;
  }

  var map = new AMap.Map('container',{
      resizeEnable: true,
      zoom: 13,
    });

  // 添加工具条
  map.plugin(["AMap.ToolBar"], function() {
    map.addControl(new AMap.ToolBar());
  });

  var markerList = null;

//  设置地图所显示的城市
  // map.setCity();

  // 删除 markers
  AMap.event.addDomListener(document.getElementById('clearMarker'), 'click', function() {
    map.remove(markers);
  }, false);

  var wtf_mode = false;

  var xlf = document.getElementById('xlf');

  function handleFile(e) {
    rABS = document.getElementsByName("userabs")[0].checked;
    use_worker = document.getElementsByName("useworker")[0].checked;

    var files = e.target.files;

    var f = files[0];
    {
      var reader = new FileReader();
      var name   = f.name;
      reader.onload = function(e) {
        var data = e.target.result;
        if(use_worker) {
          xw(data, process_wb);
        } else {
          var wb;
          if(rABS) {
            wb = X.read(data, {type: 'binary'});
          } else {
            var arr = fixdata(data);
            wb = X.read(btoa(arr), {type: 'base64'});
          }
          (process_wb(wb));
        }
      };
      if(rABS) reader.readAsBinaryString(f);
      else reader.readAsArrayBuffer(f);
    }
  }

  if(xlf.addEventListener) xlf.addEventListener('change', handleFile, false);


  function scrollListElementIntoView($listEle) {

    if (!isElementInViewport($listEle.get(0))) {
      $('#panel').scrollTop($listEle.offset().top - $listEle.parent().offset().top);
    }
  }

  function isElementInViewport(el) {
    var rect = el.getBoundingClientRect();

    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
        rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
    );
  }

  function markerClick(e) {
    infoWindow.setContent(e.target.content);
    infoWindow.open(map, e.target.getPosition());
  }
  function fixdata(data) {
      var o = "", l = 0, w = 10240;
      for(; l<data.byteLength/w; ++l) o+=String.fromCharCode.apply(null,new Uint8Array(data.slice(l*w,l*w+w)));
      o+=String.fromCharCode.apply(null, new Uint8Array(data.slice(l*w)));
      return o;
    }

    function ab2str(data) {
      var o = "", l = 0, w = 10240;
      for(; l<data.byteLength/w; ++l) o+=String.fromCharCode.apply(null,new Uint16Array(data.slice(l*w,l*w+w)));
      o+=String.fromCharCode.apply(null, new Uint16Array(data.slice(l*w)));
      return o;
    }

    function s2ab(s) {
      var b = new ArrayBuffer(s.length*2), v = new Uint16Array(b);
      for (var i=0; i != s.length; ++i) v[i] = s.charCodeAt(i);
      return [v, b];
    }

    function xw_noxfer(data, cb) {
      var worker = new Worker(XW.noxfer);
      worker.onmessage = function(e) {
        switch(e.data.t) {
          case 'ready': break;
          case 'e': console.error(e.data.d); break;
          case XW.msg: cb(JSON.parse(e.data.d)); break;
        }
      };
      var arr = rABS ? data : btoa(fixdata(data));
      worker.postMessage({d:arr,b:rABS});
    }

    function xw_xfer(data, cb) {
      var worker = new Worker(rABS ? XW.rABS : XW.norABS);
      worker.onmessage = function(e) {
        switch(e.data.t) {
          case 'ready': break;
          case 'e': console.error(e.data.d); break;
          default: xx=ab2str(e.data).replace(/\n/g,"\\n").replace(/\r/g,"\\r"); console.log("done"); cb(JSON.parse(xx)); break;
        }
      };
      if(rABS) {
        var val = s2ab(data);
        worker.postMessage(val[1], [val[1]]);
      } else {
        worker.postMessage(data, [data]);
      }
    }

    function xw(data, cb) {
      transferable = document.getElementsByName("xferable")[0].checked;
      if(transferable) xw_xfer(data, cb);
      else xw_noxfer(data, cb);
    }


    function to_json(workbook) {
      var result = {};
      workbook.SheetNames.forEach(function(sheetName) {
        var roa = X.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
        if(roa.length > 0){
          result[sheetName] = roa;
        }
      });
      return result;
    }

    function to_csv(workbook) {
      var result = [];
      workbook.SheetNames.forEach(function(sheetName) {
        var csv = X.utils.sheet_to_csv(workbook.Sheets[sheetName]);
        if(csv.length > 0){
          result.push("SHEET: " + sheetName);
          result.push("");
          result.push(csv);
        }
      });
      return result.join("\n");
    }

    function to_formulae(workbook) {
      var result = [];
      workbook.SheetNames.forEach(function(sheetName) {
        var formulae = X.utils.get_formulae(workbook.Sheets[sheetName]);
        if(formulae.length > 0){
          result.push("SHEET: " + sheetName);
          result.push("");
          result.push(formulae.join("\n"));
        }
      });
      return result.join("\n");
    }

    var tarea = document.getElementById('b64data');
    function b64it() {
      if(typeof console !== 'undefined') console.log("onload", new Date());
      var wb = X.read(tarea.value, {type: 'base64',WTF:wtf_mode});
      process_wb(wb);
    }

    var global_wb;
    function process_wb(wb) {
      global_wb  = wb;
      var output = "";

      output = JSON.stringify(to_json(wb), 2, 2);

    // 添加 N 个 markers
    var markers = [], marker_datas = [], address_count = 0;
    var message       = $('#message');
    var address_lists = output.replace(/\r/g,"").replace(/\n/g,"");
        address_lists = $.parseJSON(address_lists);
        address_lists = eval(address_lists)
        console.log(address_lists)


    AMap.plugin('AMap.Geocoder',function(){
      var geocoder = new AMap.Geocoder({
        city: "021" //城市，默认：“上海”
      });
      $.each(address_lists, function(index, address_list){

        $.each(address_list, function(index, address){
          address_count = address_list.length
          geocoder.getLocation(address.address, function(status,result){
            console.log(address.address+'--->>' + result.geocodes)
            if(status == 'complete' && result.geocodes.length){

              marker_datas.push({'id': address.order_sn, markerLabel: address.order_sn, position: [result.geocodes[0].location.lng, result.geocodes[0].location.lat], listDesc: address.address, infoWinContent: address.name});
            }else{
              address_count -= 1
              message.append('地址: '+address.address+'无法获取位置<br/>')
            }
          });
        });
      });
    });


    $('#wxloading').show();
    var interval = setInterval(function(){
      // console.log(marker_datas.length + '--' + address_count)
      if(address_count == marker_datas.length){
        marker_datas.sort(function(x, y){
          return (parseInt(x.id) - parseInt(y.id)) ;
        });
        AMapUI.loadUI(['misc/MarkerList', 'overlay/SimpleMarker', 'overlay/SimpleInfoWindow'],

          function(MarkerList, SimpleMarker, SimpleInfoWindow) {

            var $ = MarkerList.utils.$;

            var defaultIconStyle = 'red', //默认的图标样式
                hoverIconStyle = 'green', //鼠标hover时的样式
                selectedIconStyle = 'purple' //选中时的图标样式
            if(typeof markerList != "undefined" && markerList != null){
              markerList.clearData();
            }
            markerList = new MarkerList({
              map: map,
              listContainer: 'my-list',
              selectedClassNames: 'selected',
              getDataId: function(dataItem, index) {
                return dataItem.id;
              },
              getPosition: function(dataItem) {
                return dataItem.position;
              },
              getMarker: function(dataItem, context, recycledMarker) {

                if (recycledMarker) {
                  recycledMarker.setIconLabel(dataItem.id);
                  return;
                }

                return new SimpleMarker({
                  containerClassNames: 'my-marker',
                  iconStyle: defaultIconStyle,
                  iconLabel: dataItem.id
                });
              },
              getInfoWindow: function(dataItem, context, recycledInfoWindow) {
                if (recycledInfoWindow) {

                  recycledInfoWindow.setInfoTitle(dataItem.id);
                  recycledInfoWindow.setInfoBody(dataItem.infoWinContent);

                  return recycledInfoWindow;
                }

                return new SimpleInfoWindow({
                  infoTitle: dataItem.id,
                  infoBody: dataItem.infoWinContent,
                  offset: new AMap.Pixel(0, -37)
                });
              },
              //返回数据项对应的列表节点
              getListElement: function(dataItem, context, recycledListElement) {
                var tpl = '<p>'+dataItem.id+'：'+dataItem.listDesc+'<p>';
                var content = MarkerList.utils.template(tpl, {
                  dataItem: dataItem,
                  dataIndex: context.index
                });
                if (recycledListElement) {
                  recycledListElement.innerHTML = content;
                  return recycledListElement;
                }
                return '<li>' + content + '</li>';
              },
              listElementEvents: ['click', 'mouseenter', 'mouseleave'],
              markerEvents: ['click', 'mouseover', 'mouseout'],
              autoSetFitView: true
            });

          window.markerList = markerList;

          markerList.on('selectedChanged', function(event, info) {
            if (info.selected) {
              if (info.selected.marker) {
                info.selected.marker.setIconStyle(selectedIconStyle);
              }
              if (!info.sourceEventInfo.isListElementEvent) {
                if (info.selected.listElement) {
                  scrollListElementIntoView($(info.selected.listElement));
                }
              }
            }
            if (info.unSelected && info.unSelected.marker) {
              info.unSelected.marker.setIconStyle(defaultIconStyle);
            }
          });
          markerList.on('markerClick listElementClick', function(event, record) {
          });
          markerList.render(marker_datas);
        });
        clearInterval(interval);
        $('#wxloading').hide();
      }
    }, 500);
    }

    function handleDragover(e) {
      e.stopPropagation();
      e.preventDefault();
      e.dataTransfer.dropEffect = 'copy';
    }

  map.setFitView();
</script>
</body>
</html>
